import React, { useEffect, useState } from 'react'
import {
  Button,
  Form,
  message,
  Modal,
  Space,
  Table,
  Typography,
  Drawer,
  Empty,
  Dropdown,
  DatePicker,
  notification,
  Spin,
  Input,
  Select,
  Checkbox,
} from 'antd'
import * as mathjs from 'mathjs'
import useGetTableData from '@/hooks/useGetTableData'
import SearchForm from '@/components/CustomForm/SearchForm'
import { useForm } from 'antd/es/form/Form'
import PageContainer from '@/components/PageContainer'
import { useIndexColumns, useLimitColumns, useBillDetailColumns, useFabricTableDataColumns } from './columns'
import { BillInfoVO, ITableData, PurchaseFabricOrderVO } from './types'
import { EditFormVertical } from '@/components/CustomForm'
import CustomTable from '@/components/CustomTable'
import { applicationTypeEnum, IMPORT_FILE_ENUM, OperationPurchaseActionsType } from '@/constant'
import { useNavigate, useSearchParams } from 'react-router-dom'
import { useAppSelector } from '@/store/hooks'
import './index.less'
import { ImportOutlined, DownOutlined, PlusOutlined, ExclamationCircleOutlined, UserOutlined } from '@ant-design/icons'
import {
  auditPurchaseOrder,
  cancelPurchase,
  confirmBill,
  batchExportProduceSchedule,
  exportPurchaseOrder,
  getBillInfo,
  importPurchaseOrder,
  importPurchaseProduceSchedule,
  pagePurchaseOrderList,
  qualityCreate,
  rejectProduce,
  retryPushingCenter,
  submitPurchaseOrder,
  terminatePurchase,
  updateAppointmentFloatingLimit,
  updatePurchaseInfo,
  batchImportDeliveryTime,
  purchaseOrderTodo,
  updateTransferRule,
  getPurchaseFabric,
  getSupplierByFabricCode,
  purchaseOrderUpdateQC,
  savePurchaseFabric,
  purchaseOrderUpdateTrackPerson,
} from '@/api/purchase'
import dayjs from 'dayjs'
import {
  ORDER_ACCOUNTING_STATUS_OPTIONS_SUPPLIER,
  ORDER_STATUS_OPTIONS,
  ORDER_STATUS_OPTIONS_SUPPLIER,
  TRANSFER_TYPE_OPTIONS,
} from '@/constant/purchase'
import { IOptionClass } from '@/pages/Goods/Plan'
import { getProductClassConfigByType, getSpuOptions } from '@/api/goods'
import {
  FIRST_ORDER_RETURN_ORDER_OPTIONS,
  ORDER_ACCOUNTING_STATUS_OPTIONS,
  ORDER_CONTRACT_STATUS_OPTIONS,
  PURCHASEWAY_OPTIONS,
} from '@/constant/purchase'
import { getUserOptions } from '@/api/user'
import { useChangeQCConfig, useChangeTrackPersonConfig, useFormAudit, useFormQc } from './useForm'
import { exportNotification, flattenData, getRecentSixMonths, importNotification } from '@/utils/util'
import ImportFileModal from '@/components/ImportFileModal'
import PermissionButton from '@/components/PermissionButton'
import useGetClassIds from '@/hooks/useGetClassIds'
import useSearchSupplier from '@/hooks/useSearchSupplier'
import { TwoDateVerifyCanEqual } from '@/utils/validator'
import useCachePage from '@/hooks/useCachePage'
import useSearchUser from '@/hooks/useSearchUser'
import useModal from '@/hooks/useModal'
export interface IOptionClassEdit extends IOptionClass {
  isEdit?: boolean
  appointmentFloatingLimit?: string
}
const Index: React.FC = () => {
  let FTimeout: ITimeoutType
  let SpuTimeout: ITimeoutType
  const navigate = useNavigate()
  const [form] = useForm()
  const [formAudit] = useForm()
  const [formBill] = useForm()
  const [formQc] = useForm()
  const [FormDelivery] = useForm()
  const [FormReturnBack] = useForm()
  const [FormUpload] = useForm()
  const [isUploadFileShow, setisUploadFileShow] = useState<boolean>(false)
  const [billConfirmLoading, setbillConfirmLoading] = useState<boolean>(false)
  const DICTDATA = useAppSelector((state) => state.login.DICTDATA)
  const [tempCode, setTempcode] = useState<
    | IMPORT_FILE_ENUM.PURCHASEW_ORDER_IMPORT
    | IMPORT_FILE_ENUM.PURCHASEW_PROCESS_IMPORT
    | IMPORT_FILE_ENUM.PURCHASEW_DELIVERYTIME_IMPORT
  >(IMPORT_FILE_ENUM.PURCHASEW_ORDER_IMPORT)
  const [CurrentInfo, setCurrentInfo] = useState<Record<string, any>>({})
  const [auditDrawerShow, setauditDrawerShow] = useState<boolean>(false)
  const [qcOrderShow, setqcOrderShow] = useState<boolean>(false)
  const [billModalShow, setbillModalShow] = useState<boolean>(false)
  const [goodsLimitModalShow, setgoodsLimitModalShow] = useState<boolean>(false)
  const [isModalShow, setisModalShow] = useState<boolean>(false)
  const [isReturnModalShow, setisReturnModalShow] = useState<boolean>(false)
  const [exportLoading, setexportLoading] = useState(false)
  const [searchOptions, setOptions] = useState<IOptionItem[]>([])
  const [SpuOptions, setSpuOptions] = useState<IOptionItem[]>([])
  const [FabricSupplierOptions, setFabricSupplierOptions] = useState<IOptionItem[]>([])
  const [selectKeys, setselectKeys] = useState<React.Key[]>([])
  const [selectInfos, setselectInfos] = useState<ITableData[]>([])
  const [tableData, settableData] = useState<ITableData[]>([])
  const [SkuOptions] = useState<IOptionItem[]>([])
  const [classBig, setclassBig] = useState<IOptionItem[]>([])
  const [billTableInfo, setBillTableInfo] = useState<{ purchaseOrderFinance: string; billInfoList: BillInfoVO[] }>({
    purchaseOrderFinance: '',
    billInfoList: [],
  })
  const [CountNum, setCountNum] = useState<{ waitConfirmBillNum: number; nonFabricOrderNum: number }>({
    waitConfirmBillNum: 0,
    nonFabricOrderNum: 0,
  })
  const [billTableLoading, setbillTableLoading] = useState(false)
  const buttonCodeList = useAppSelector((state) => state.login.buttonCodeList) || []
  const [menuItems, setmenuItems] = useState<{ key: string; label: string | React.ReactNode }[]>([])
  const [menuItemsExport, setmenuItemsExport] = useState<{ key: string; label: string }[]>([])
  const { SupplierOption, handleSearchSupplier, setSupplierOption } = useSearchSupplier('supplierId')
  const defaultDateRange = getRecentSixMonths()
  const applicationId = useAppSelector((state) => state.user.user_info.applicationId)
  const isRoot = applicationId == applicationTypeEnum.SOP_SEVENFUN_WEB
  const [query] = useSearchParams()
  const customSearchType = query.get('customSearchType') || ''
  // table修改的
  const [classIdOptionsTable, setclassIdOptionstable] = useState<IOptionClassEdit[]>([])
  const { classIdOptions, settinyClassIds, tinyClassIds, handleClassIdChange } = useGetClassIds()
  const { setCachePage, getCachePage } = useCachePage()
  //跟单
  const { UserOptions, handleSearchUser, setUserOptions } = useSearchUser()

  const {
    UserOptions: UserOptionsW,
    handleSearchUser: handleSearchUserW,
    setUserOptions: setUserOptionsW,
  } = useSearchUser('workId')

  const { UserOptions: UserOptionsByTrackPerson, handleSearchUser: handleSearchUserByTrackPerson } = useSearchUser(
    'workId',
    { roleIds: ['61', '64'] },
  )
  //qc
  const { UserOptions: UserOptionsByQc, handleSearchUser: handleSearchUserByQc } = useSearchUser(
    'workId',
    {
      roleIds: ['62'],
    },
    true,
  )

  const {
    UserOptions: UserOptionsByQcDropDown,
    setUserOptions: setUserOptionsByQcDropDown,
    handleSearchUser: handleSearchUserByQcDropDown,
  } = useSearchUser('workId')

  const [spinning, setspinning] = useState<boolean>(false)
  const TransferRulesModal = useModal({
    onSuccess: () => {
      message.success('操作成功')
      TransferRulesModal.closeModal()
      setselectKeys([])
      setselectInfos([])
    },
    onFail: () => {
      TransferRulesModal.closeModal()
      setselectKeys([])
      setselectInfos([])
    },
    onReload: () => {
      reloadPage()
    },
  })
  const changeQCModal = useModal({
    onSuccess: () => {
      message.success('操作成功')
      changeQCModal.closeModal()
      setselectKeys([])
      setselectInfos([])
    },
    onFail: () => {
      changeQCModal.closeModal()
      setselectKeys([])
      setselectInfos([])
    },
    onReload: () => {
      reloadPage()
    },
  })
  const changeTrackPersonModal = useModal({
    onSuccess: () => {
      message.success('操作成功')
      changeTrackPersonModal.closeModal()
      setselectKeys([])
      setselectInfos([])
    },
    onFail: () => {
      changeTrackPersonModal.closeModal()
      setselectKeys([])
      setselectInfos([])
    },
    onReload: () => {
      reloadPage()
    },
  })
  const DistributeFabricModal = useModal({
    onSuccess: () => {
      message.success('操作成功')
      DistributeFabricModal.closeModal()
      setselectKeys([])
      setselectInfos([])
    },
    onReload: () => {
      reloadPage()
    },
  })
  const [FabricTableData, setFabricTableData] = useState<PurchaseFabricOrderVO[]>([])
  const { tableProps, params, setParams, search, reset } = useGetTableData<ITableData>(pagePurchaseOrderList, {
    form: form,
    defaultFieldsParams: {
      officialOrderTimeStart: defaultDateRange,
      billStatus: isRoot ? null : 1,
      statuses: isRoot ? [0, 1, 2, 3, 5] : [2],
    },
    immediatelySend: false,
    cachePageCallback: (current, size, prevSize) => {
      const cacheData = getCachePage()
      setCachePage({
        ...cacheData,
        current: prevSize === size ? current : 1,
        size,
      })
    },
  })
  useEffect(() => {
    settableData(tableProps?.dataSource || [])
  }, [tableProps?.dataSource])
  useEffect(() => {
    getpurchaseOrderTodo()
    const items: { key: string; label: string | React.ReactNode }[] = []
    if (buttonCodeList.includes('submitPurchase')) {
      items.push({
        key: OperationPurchaseActionsType.SEND + '',
        label: '提交',
      })
    }
    if (buttonCodeList.includes('checkPurchase')) {
      items.push({
        key: OperationPurchaseActionsType.EXAMINE + '',
        label: '审核',
      })
    }
    if (buttonCodeList.includes('confirmPurchaseFinance')) {
      items.push({
        key: OperationPurchaseActionsType.CONFIRM + '',
        label: '确认账期',
      })
    }
    if (buttonCodeList.includes('rejectPurchase')) {
      items.push({
        key: OperationPurchaseActionsType.RETURN + '',
        label: '生产驳回',
      })
    }
    if (buttonCodeList.includes('breakPurchase')) {
      items.push({
        key: OperationPurchaseActionsType.BREAK + '',
        label: (
          <Typography.Text type="warning" strong>
            中止订单
          </Typography.Text>
        ),
      })
    }
    if (buttonCodeList.includes('cancelPurchase')) {
      items.push({
        key: OperationPurchaseActionsType.Cancel + '',
        label: (
          <Typography.Text type="danger" strong>
            取消采购订单
          </Typography.Text>
        ),
      })
    }
    if (buttonCodeList.includes('pushPurchase')) {
      items.push({
        key: 'PUSH',
        label: '触发CB推送',
      })
    }
    setmenuItems(items)
    const itemsExport: { key: string; label: string }[] = []
    if (buttonCodeList.includes('exportSchedule')) {
      itemsExport.push({
        key: '1',
        label: '导出生产进度',
      })
    }
    if (buttonCodeList.includes('exportPurchase')) {
      itemsExport.push({
        key: '2',
        label: '导出采购明细',
      })
    }
    setmenuItemsExport(itemsExport)
    getProductClassConfig()
    if (customSearchType === '1') {
      form.resetFields()
      form.setFieldsValue({
        billStatus: 0,
        statuses: [2],
      })
      setTimeout(() => {
        search({ billStatus: 0, statuses: [2], current: 1, size: params.size, officialOrderTimeStart: null })
      }, 1)
    } else if (customSearchType === '2') {
      form.resetFields()
      form.setFieldsValue({
        scheduleIsMaintain: 0,
        statuses: [2],
      })
      setTimeout(() => {
        search({ scheduleIsMaintain: 0, statuses: [2], current: 1, size: params.size, officialOrderTimeStart: null })
      }, 1)
    } else {
      handleCacheData()
    }
  }, [])
  const handleCacheData = () => {
    const cacheData = getCachePage()
    if (cacheData == null) {
      const paramsData = {
        ...params,
        officialOrderTimeStart: dayjs(defaultDateRange[0]).format('YYYY-MM-DD HH:mm:ss'),
        officialOrderTimeEnd: dayjs(defaultDateRange[1]).format('YYYY-MM-DD HH:mm:ss'),
        billStatus: isRoot ? null : 1,
        statuses: isRoot ? [0, 1, 2, 3, 5] : [2],
      }
      search({
        ...paramsData,
      })
      setCachePage({
        ...paramsData,
      })
    } else {
      if (cacheData.tinyClassId && cacheData.tinyClassId.length > 0) {
        settinyClassIds(cacheData.queryClassIdList)
      }
      form.setFieldsValue({
        ...cacheData,
        createTimeStart:
          cacheData.createTimeStart && cacheData.createTimeEnd
            ? [dayjs(cacheData.createTimeStart), dayjs(cacheData.createTimeEnd)]
            : null,
        officialOrderTimeStart:
          cacheData.officialOrderTimeStart && cacheData.officialOrderTimeEnd
            ? [dayjs(cacheData.officialOrderTimeStart), dayjs(cacheData.officialOrderTimeEnd)]
            : null,
        requiredArrivalTimeStart: isRoot
          ? cacheData.requiredArrivalTimeStart && cacheData.requiredArrivalTimeEnd
            ? [dayjs(cacheData.requiredArrivalTimeStart), dayjs(cacheData.requiredArrivalTimeEnd)]
            : null
          : null,
        queryClassIdList: cacheData.tinyClassId,
        statuses: cacheData.statuses != null ? cacheData.statuses : null,
        queryQcIsNull: cacheData.queryQcIsNull ? 1 : null,
      })
      setSpuOptions(cacheData?.SpuOptions || [])
      setSupplierOption(cacheData?.SupplierOption || [])
      setOptions(cacheData?.searchOptions || [])
      setUserOptions(cacheData?.UserOptions || [])
      setUserOptionsByQcDropDown(cacheData?.UserOptionsByQcDropDown || [])
      delete cacheData.tinyClassId
      delete cacheData.SpuOptions
      delete cacheData.SupplierOption
      delete cacheData.searchOptions
      delete cacheData.UserOptions
      delete cacheData.UserOptionsByQcDropDown
      search({
        ...cacheData,
        createTimeStart: cacheData.createTimeStart ? cacheData.createTimeStart : null,
        createTimeEnd: cacheData.createTimeEnd ? cacheData.createTimeEnd : null,
        officialOrderTimeStart: cacheData.officialOrderTimeStart ? cacheData.officialOrderTimeStart : null,
        officialOrderTimeEnd: cacheData.officialOrderTimeEnd ? cacheData.officialOrderTimeEnd : null,
        billStatus: isRoot ? cacheData.billStatus : 1,
        statuses: isRoot ? (cacheData.statuses != null ? cacheData.statuses : null) : [2],
        createBy: isRoot ? (cacheData.createBy ? cacheData.createBy : null) : null,
        trackOrderPerson: isRoot ? (cacheData.trackOrderPerson ? cacheData.trackOrderPerson : null) : null,
        pushStatus: isRoot ? cacheData.pushStatus : null,
        requiredArrivalTimeStart: isRoot
          ? cacheData?.requiredArrivalTimeStart
            ? cacheData?.requiredArrivalTimeStart
            : null
          : null,
        requiredArrivalTimeEnd: isRoot
          ? cacheData?.requiredArrivalTimeEnd
            ? cacheData?.requiredArrivalTimeEnd
            : null
          : null,
        queryQcIsNull: cacheData.queryQcIsNull ? 1 : null,
        qcDefaultUserWorkId: cacheData.qcDefaultUserWorkId || null,
      })
    }
  }
  const getpurchaseOrderTodo = async () => {
    const res = await purchaseOrderTodo<{ waitConfirmBillNum: number; nonFabricOrderNum: number }>({})
    if (res.code == 200) {
      setCountNum(res?.data)
    } else {
      setCountNum({
        waitConfirmBillNum: 0,
        nonFabricOrderNum: 0,
      })
    }
  }
  const selectRows = (keys: React.Key[], info: ITableData[]) => {
    setselectKeys(keys)
    setselectInfos(info)
  }
  const getProductClassConfig = async () => {
    const res = await getProductClassConfigByType<{
      className: string
      classConfigId: string | number
      appointmentFloatingLimit: string
    }>({ type: 1, auth: 1 })
    const classIdOptions =
      res?.data?.map((item) => {
        return {
          label: item.className,
          value: item.classConfigId,
          isLeaf: false,
        }
      }) || []
    setclassBig(classIdOptions)
    const classIdOptionsItems =
      res?.data?.map((item) => {
        return {
          label: item.className,
          value: item.classConfigId,
          isLeaf: false,
          appointmentFloatingLimit: item.appointmentFloatingLimit,
        }
      }) || []
    setclassIdOptionstable(classIdOptionsItems)
  }
  const onCancel = () => {
    setauditDrawerShow(false)
    formAudit.resetFields()
    setbillModalShow(false)
    formBill.resetFields()
    setqcOrderShow(false)
    formQc.resetFields()
    setgoodsLimitModalShow(false)
    setBillTableInfo({
      purchaseOrderFinance: '',
      billInfoList: [],
    })
    setCurrentInfo({})
  }
  const onConfirmData = async (values: any) => {
    console.log(values, 'values')
    const res = await auditPurchaseOrder({
      ...values,
      purchaseIds: selectKeys,
      status: values.auditStatus === 1 ? 2 : 0,
    }).finally(() => {
      reloadPage()
      onCancel()
      setselectKeys([])
      setselectInfos([])
    })
    if (res.code === 200) {
      message.success('操作成功')
    }
    if (res.code === 820000 && res.failInfo) {
      const failInfo = JSON.parse(res.failInfo)?.map((item: any) => {
        return (
          <div key={item.purchaseOrderCode}>
            {item.purchaseOrderCode},{item.reason}
          </div>
        )
      })
      notification.open({
        type: 'warning',
        message: res.msg,
        description: failInfo,
      })
    }
  }
  const onBillClick = async (info: ITableData) => {
    setbillModalShow(true)
    setbillTableLoading(true)
    setCurrentInfo(info)
    const res = await getBillInfo({ purchaseOrderCode: info.purchaseOrderCode }).finally(() =>
      setbillTableLoading(false),
    )
    setBillTableInfo(
      res?.data || {
        purchaseOrderFinance: '',
        billInfoList: [],
      },
    )
  }
  const onConfirmBillSingle = () => {
    const instance = Modal.confirm({
      title: '提示',
      content: '确认要确认账期吗?',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        setbillConfirmLoading(true)
        const res = await confirmBill({ purchaseIds: [CurrentInfo.id], billStatus: 1 }).finally(() => {
          reloadPage()
          setselectKeys([])
          setselectInfos([])
          onCancel()
          instance.destroy()
          setbillConfirmLoading(false)
        })
        if (res.code === 200) {
          message.success('操作成功')
        }
        if (res.code === 820000 && res.failInfo) {
          const failInfo = JSON.parse(res.failInfo)?.map((item: any) => {
            return (
              <div key={item.purchaseOrderCode}>
                {item.purchaseOrderCode},{item.reason}
              </div>
            )
          })
          notification.open({
            type: 'warning',
            message: res.msg,
            description: failInfo,
          })
        }
      },
    })
  }
  const onUploadFileCancel = () => {
    FormUpload.resetFields()
    setisUploadFileShow(false)
  }
  const onUploadFileOk = async () => {
    const { file } = await FormUpload.validateFields()
    setexportLoading(true)
    if (tempCode === IMPORT_FILE_ENUM.PURCHASEW_ORDER_IMPORT) {
      const res = await importPurchaseOrder<{ linkUrl: string }>(file).finally(() => {
        setexportLoading(false)
        FormUpload.resetFields()
      })
      if (res.code === 200) {
        notification.success({
          message: '任务已生成，请前往右上角任务中心中查看',
        })
        reloadPage()
        onUploadFileCancel()
      }
    }
    if (tempCode === IMPORT_FILE_ENUM.PURCHASEW_PROCESS_IMPORT) {
      const res = await importPurchaseProduceSchedule<{ linkUrl: string }>(file).finally(() => {
        setexportLoading(false)
        FormUpload.resetFields()
      })
      if (res.code === 200) {
        importNotification(res?.data?.linkUrl)
        reloadPage()
        onUploadFileCancel()
      }
    }
    if (tempCode === IMPORT_FILE_ENUM.PURCHASEW_DELIVERYTIME_IMPORT) {
      const res = await batchImportDeliveryTime<{ linkUrl: string }>(file).finally(() => {
        setexportLoading(false)
        reloadPage()
        onUploadFileCancel()
        FormUpload.resetFields()
      })
      if (res.code === 200) {
        notification.open({
          type: 'success',
          message: '所有数据导入成功',
          duration: 5,
        })
      }
      if (res?.code === 820000) {
        const key = `open${Date.now()}`
        notification.open({
          type: 'warning',
          message: <div style={{ fontWeight: 500, userSelect: 'none' }}>存在导入失败的数据</div>,
          description: res?.msg,
          duration: null,
          key,
        })
      }
    }
  }
  const onConfirmQC = async (values: any) => {
    const paramsData = {
      qualityPhase: values.qualityPhase,
      scheduleQualityTime: dayjs(values.scheduleQualityTime).format('YYYY-MM-DD'),
      purchaseOrderCodes: selectInfos?.map((item) => item.purchaseOrderCode),
    }
    const res = await qualityCreate(paramsData).finally(() => {
      onCancel()
    })
    if (res.code === 200) {
      message.success('操作成功')
      reloadPage()
      setselectKeys([])
      setselectInfos([])
    }
    if (res.code === 820000 && res.failInfo) {
      const failInfo = JSON.parse(res.failInfo)?.map((item: string) => {
        return <div key={item}>{item}</div>
      })
      notification.open({
        type: 'warning',
        message: res.msg,
        description: failInfo,
      })
    }
    if (res.code === 820005 && typeof res.failInfo == 'string' && typeof res.msg == 'string') {
      const instance = Modal.confirm({
        title: res.msg,
        content: res.failInfo,
        okText: '确定',
        cancelText: '取消',
        onOk: async () => {
          const res = await qualityCreate({ ...paramsData, allowRepeat: 1 }).finally(() => instance.destroy())
          if (res.code === 200) {
            message.success('操作成功')
            reloadPage()
            setselectKeys([])
            setselectInfos([])
          }
        },
        onCancel: () => {
          setselectKeys([])
          setselectInfos([])
        },
      })
    }
  }
  const handleSearchSpuOptions = (newValue = '') => {
    if (!newValue) return
    if (SpuTimeout) {
      clearTimeout(SpuTimeout)
      SpuTimeout = null
    }
    const getOptions = async () => {
      const res = await getSpuOptions<{
        spuName: string
        spuCode: string
        designCode: string
      }>({ keyword: newValue })
      if (res.code === 200) {
        const data =
          res?.data?.map((item) => {
            return {
              label: `${item?.spuCode}｜${item.spuName}${item?.designCode ? '｜' + item?.designCode : ''}`,
              value: item.spuCode,
            }
          }) || []
        setSpuOptions(data)
      }
    }
    SpuTimeout = setTimeout(getOptions, 500)
  }

  const handleSearchSupplierF = (fabricCode: string) => {
    if (!fabricCode) return
    if (FTimeout) {
      clearTimeout(FTimeout)
      FTimeout = null
    }
    const getOptions = async () => {
      const res = await getSupplierByFabricCode<{
        supplierCode: string
        supplierName: string
      }>({ fabricCode })
      if (res.code === 200) {
        const data =
          res?.data?.map((item) => {
            return {
              label: item.supplierName,
              value: item.supplierCode,
            }
          }) || []
        setFabricSupplierOptions(data)
      }
    }
    FTimeout = setTimeout(getOptions, 500)
  }
  const onConfirmGoodsLimit = async () => {
    const params = classIdOptionsTable
      ?.filter((item) => Object.prototype.hasOwnProperty.call(item, 'isEdit'))
      ?.map((item) => {
        return {
          classConfigId: item.value,
          appointmentFloatingLimit: item.appointmentFloatingLimit || '',
        }
      })
    if (params?.length === 0) {
      message.warning('未找到修改的数据！')
      return
    }
    const res = await updateAppointmentFloatingLimit(params)
    if (res.code === 200) {
      message.success('操作成功')
      onCancel()
      getProductClassConfig()
    }
  }
  const handleClickMore = async (info: any) => {
    if (selectKeys.length === 0) {
      message.warning('请选勾选订单！')
      return
    }
    if (info.key == OperationPurchaseActionsType.SEND) {
      const res = await submitPurchaseOrder({ purchaseIds: selectKeys, status: 1 }).finally(() => {
        reloadPage()
        onCancel()
        setselectKeys([])
        setselectInfos([])
      })
      if (res.code === 200) {
        message.success('操作成功')
      }
      if (res.code === 820000 && res.failInfo) {
        const failInfo = JSON.parse(res.failInfo)?.map((item: string) => {
          return <div key={item}>{item}</div>
        })
        notification.open({
          type: 'warning',
          message: res.msg,
          description: failInfo,
        })
      }
    } else if (info.key == OperationPurchaseActionsType.EXAMINE) {
      setauditDrawerShow(true)
    } else if (info.key == OperationPurchaseActionsType.CONFIRM) {
      const res = await confirmBill({ purchaseIds: selectKeys, billStatus: 1 }).finally(() => {
        reloadPage()
        setselectKeys([])
        setselectInfos([])
      })
      if (res.code === 200) {
        message.success('操作成功')
      }
      if (res.code === 820000 && res.failInfo) {
        const failInfo = JSON.parse(res.failInfo)?.map((item: any) => {
          return (
            <div key={item.purchaseOrderCode}>
              {item.purchaseOrderCode},{item.reason}
            </div>
          )
        })
        notification.open({
          type: 'warning',
          message: res.msg,
          description: failInfo,
        })
      }
    } else if (info.key == OperationPurchaseActionsType.RETURN) {
      setisReturnModalShow(true)
    } else if (info.key == OperationPurchaseActionsType.BREAK) {
      const instance = Modal.confirm({
        title: '提示',
        content: '确定中止订单吗?',
        okText: '确认',
        cancelText: '取消',
        icon: <ExclamationCircleOutlined />,
        onOk: async () => {
          const res = await terminatePurchase({ purchaseIds: selectKeys, status: 5 }).finally(() => {
            reloadPage()
            setselectKeys([])
            setselectInfos([])
            instance.destroy()
          })
          if (res.code === 200) {
            message.success('操作成功')
          }
          if (res.code === 820000 && res.failInfo) {
            const failInfo = JSON.parse(res.failInfo)?.map((item: any) => {
              return (
                <div key={item.purchaseOrderCode}>
                  {item.purchaseOrderCode},{item.reason}
                </div>
              )
            })
            notification.open({
              type: 'warning',
              message: res.msg,
              description: failInfo,
            })
          }
        },
      })
    } else if (info.key == OperationPurchaseActionsType.Cancel) {
      Modal.confirm({
        title: '提示',
        content: '确定取消采购订单吗?',
        okText: '确认',
        cancelText: '取消',
        icon: <ExclamationCircleOutlined />,
        onOk: async () => {
          const res = await cancelPurchase({ purchaseIds: selectKeys, status: 4 }).finally(() => {
            reloadPage()
            setselectKeys([])
            setselectInfos([])
          })
          if (res.code === 200) {
            message.success('操作成功')
          }
          if (res.code === 820000 && res.failInfo) {
            const failInfo = JSON.parse(res.failInfo)?.map((item: any) => {
              return (
                <div key={item.purchaseOrderCode}>
                  {item.purchaseOrderCode},{item.reason}
                </div>
              )
            })
            notification.open({
              type: 'warning',
              message: res.msg,
              description: failInfo,
            })
          }
        },
      })
    } else if (info.key == 'PUSH') {
      const res = await retryPushingCenter({
        purchaseIds: selectInfos.map((item) => item.id),
        purchaseOrderCodes: selectInfos.map((item) => item.purchaseOrderCode),
      })
      if (res.code === 200) {
        message.success('触发推送成功，请稍后查看！')
        setselectKeys([])
        setselectInfos([])
        reloadPage()
      }
    }
  }
  const handleClickMoreExport = async (info: any) => {
    const paramsData: Record<string, any> = {}
    if (selectKeys.length > 0) {
      paramsData.purchaseOrderCodes = selectInfos?.map((item) => item.purchaseOrderCode)
    } else {
      Object.assign(paramsData, params)
    }
    if (info.key == '1') {
      setexportLoading(true)
      setspinning(true)
      const res = await batchExportProduceSchedule(paramsData)
        .catch(() => setspinning(false))
        .finally(() => {
          setexportLoading(false)
          setselectKeys([])
          setselectInfos([])
        })
      if (res?.code === 200 && res?.data) {
        await exportNotification(res?.data, navigate).finally(() => setspinning(false))
      }
    } else if (info.key == '2') {
      setexportLoading(true)
      setspinning(true)
      const res = await exportPurchaseOrder(paramsData)
        .catch(() => setspinning(false))
        .finally(() => {
          setexportLoading(false)
          setselectKeys([])
          setselectInfos([])
        })
      if (res?.code === 200 && res?.data) {
        await exportNotification(res?.data, navigate).finally(() => setspinning(false))
      }
    }
  }
  const onEditDeliveryTime = (info: ITableData) => {
    setCurrentInfo(info)
    setisModalShow(true)
    FormDelivery.setFieldsValue({
      deliveryTime: info?.deliveryTime && dayjs(info.deliveryTime),
    })
  }
  const onSaveUser = async (rows: ITableData, isFlush: boolean) => {
    if (isFlush) {
      if (!rows.trackOrderPersonWorkId || !rows.trackOrderPerson) {
        message.warning('请选择供应链跟单后后再保存！')
        return
      }
      const res = await updatePurchaseInfo({
        id: rows.id,
        trackOrderPersonWorkId: rows.trackOrderPersonWorkId,
        trackOrderPerson: rows.trackOrderPerson,
      })
      if (res.code == 200) {
        message.success('操作成功')
      }
    }
    reloadPage()
  }
  const onModalCancel = () => {
    setisModalShow(false)
    setCurrentInfo({})
    FormDelivery.resetFields()
    setisReturnModalShow(false)
    FormReturnBack.resetFields()
  }
  const onSendOk = async () => {
    const data = await FormDelivery.validateFields()
    const res = await updatePurchaseInfo({
      id: CurrentInfo.id,
      deliveryTime: dayjs(data.deliveryTime).format('YYYY-MM-DD'),
    })
    if (res.code == 200) {
      message.success('操作成功')
      reloadPage()
      onModalCancel()
    }
  }
  const onReturnBack = async () => {
    const data = await FormReturnBack.validateFields()
    setexportLoading(true)
    const res = await rejectProduce({
      purchaseIds: selectKeys,
      status: 0,
      billStatus: 0,
      rejectRemark: data.rejectRemark,
    }).finally(() => {
      reloadPage()
      setselectKeys([])
      setselectInfos([])
      onModalCancel()
      setexportLoading(false)
    })
    if (res.code === 200) {
      message.success('操作成功')
    }
    if (res.code === 820000 && res.failInfo) {
      const failInfo = JSON.parse(res.failInfo)?.map((item: any) => {
        return (
          <div key={item.purchaseOrderCode}>
            {item.purchaseOrderCode},{item.reason}
          </div>
        )
      })
      notification.open({
        type: 'warning',
        message: res.msg,
        description: failInfo,
      })
    }
  }
  const reloadPage = () => {
    search(params)
    getpurchaseOrderTodo()
  }
  return (
    <PageContainer className="purchase_order_page">
      {isRoot && (
        <div className="waittodo_box">
          <div className="wait_main">
            <div className="wm_item">
              <div className="wm_item_title">账期待确认</div>
              <div className="wm_item_num">
                <Typography.Link
                  underline
                  onClick={() => {
                    form.resetFields()
                    form.setFieldsValue({
                      billStatus: 0,
                      statuses: [2],
                    })
                    search({
                      ...form.getFieldsValue(),
                      createTimeEnd: null,
                      officialOrderTimeEnd: null,
                      requiredArrivalTimeEnd: null,
                      current: 1,
                      size: 10,
                    })
                    setselectKeys([])
                    setselectInfos([])
                  }}
                >
                  {CountNum.waitConfirmBillNum || 0}单
                </Typography.Link>
              </div>
            </div>
            <div className="wm_item">
              <div className="wm_item_title">面料订单待下发</div>
              <div className="wm_item_num">
                <Typography.Link
                  underline
                  onClick={() => {
                    form.resetFields()
                    form.setFieldsValue({
                      fabricOrderStatus: 0,
                      fabricIntensive: 1,
                      statuses: [2],
                    })
                    search({
                      ...form.getFieldsValue(),
                      createTimeEnd: null,
                      officialOrderTimeEnd: null,
                      requiredArrivalTimeEnd: null,
                      current: 1,
                      size: 10,
                    })
                    setselectKeys([])
                    setselectInfos([])
                  }}
                >
                  {CountNum.nonFabricOrderNum || 0}单
                </Typography.Link>
              </div>
            </div>
          </div>
        </div>
      )}
      <SearchForm
        params={params}
        form={form}
        searchConfig={[
          {
            label: '采购订单',
            name: 'purchaseOrderCodes',
            placeholder: '多个单号间需要换行或使用","分隔',
            type: 'Select',
            config: {
              mode: 'tags',
              maxTagCount: 'responsive',
              tokenSeparators: [',', '，', '\n', '\r', '\r\n'],
              notFoundContent: null,
            },
          },
          { label: '正式订单时间', name: 'officialOrderTimeStart', type: 'RangePicker', config: { showTime: true } },
          {
            label: '订单状态',
            name: 'statuses',
            type: 'Select',
            option: isRoot ? ORDER_STATUS_OPTIONS : ORDER_STATUS_OPTIONS_SUPPLIER,
            config: {
              mode: 'multiple',
              maxTagCount: 'responsive',
              optionFilterProp: 'label',
            },
          },
          {
            name: 'supplierIdList',
            label: '供应商',
            type: 'Select',
            option: SupplierOption,
            config: {
              suffixIcon: null,
              showSearch: true,
              optionFilterProp: 'label',
              mode: 'multiple',
              maxTagCount: 'responsive',
              filterOption: false,
              onSearch: handleSearchSupplier,
              notFoundContent: <Empty description="请输入内容搜索" image={Empty.PRESENTED_IMAGE_SIMPLE} />,
            },
          },
          {
            label: '大类',
            name: 'firstClassConfigIdList',
            type: 'Select',
            option: classBig,
            config: {
              suffixIcon: null,
              showSearch: true,
              optionFilterProp: 'label',
              mode: 'multiple',
              maxTagCount: 'responsive',
            },
          },
          {
            name: 'queryClassIdList',
            label: '款式分类',
            type: 'Cascader',
            option: classIdOptions,
            placeholder: '请选择款式分类',
            config: {
              changeOnSelect: true,
              onChange: handleClassIdChange,
              onClear: () => settinyClassIds([]),
              fieldNames: { label: 'className', value: 'classConfigId', children: 'childrenList' },
            },
          },
          { label: '要求到货时间', name: 'requiredArrivalTimeStart', type: 'RangePicker', hidden: !isRoot },
          {
            label: '采购方式',
            name: 'purchaseType',
            type: 'Select',
            option: PURCHASEWAY_OPTIONS,
            config: {
              showSearch: true,
              optionFilterProp: 'label',
            },
          },
          { label: '首单/返单', name: 'orderType', type: 'Select', option: FIRST_ORDER_RETURN_ORDER_OPTIONS },
          {
            label: '年份',
            name: 'year',
            type: 'FixedDatePicker',
            placeholder: '请选择年份',
            config: {
              picker: 'year',
              format: 'YYYY',
              customFormat: 'YYYY',
            },
          },
          {
            name: 'seasonCode',
            label: '订单季节',
            type: 'Select',
            option: DICTDATA.order_season,
            placeholder: '请选择订单季节',
            config: {
              showSearch: true,
              optionFilterProp: 'label',
            },
          },
          { label: '创建时间', name: 'createTimeStart', type: 'RangePicker', config: { showTime: true } },
          { label: '订单合同状态', name: 'contractStatus', type: 'Select', option: ORDER_CONTRACT_STATUS_OPTIONS },
          {
            label: '订单账期状态',
            name: 'billStatus',
            type: 'Select',
            option: isRoot ? ORDER_ACCOUNTING_STATUS_OPTIONS : ORDER_ACCOUNTING_STATUS_OPTIONS_SUPPLIER,
            hidden: !isRoot,
          },
          {
            label: '生产计划状态',
            name: 'scheduleIsMaintain',
            type: 'Select',
            option: [
              { label: '是', value: 1 },
              { label: '否', value: 0 },
            ],
          },
          {
            label: '供应链跟单',
            name: 'trackOrderPerson',
            type: 'Select',
            option: UserOptions,
            hidden: !isRoot,
            config: {
              suffixIcon: null,
              showSearch: true,
              optionFilterProp: 'label',
              filterOption: false,
              onSearch: handleSearchUser,
              notFoundContent: <Empty description="请输入内容搜索" image={Empty.PRESENTED_IMAGE_SIMPLE} />,
              fieldNames: { label: 'label', value: 'workId' },
            },
          },
          {
            label: 'QC人员',
            type: 'Custom',
            slot: (
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <Form.Item name="qcDefaultUserWorkId" label="" style={{ flex: 3 }}>
                  <Select
                    style={{ width: '100%' }}
                    placeholder="请选择QC人员"
                    options={UserOptionsByQcDropDown}
                    suffixIcon={null}
                    showSearch
                    optionFilterProp="label"
                    filterOption={false}
                    onSearch={handleSearchUserByQcDropDown}
                    fieldNames={{ label: 'label', value: 'workId' }}
                    notFoundContent={<Empty description="请输入内容搜索" image={Empty.PRESENTED_IMAGE_SIMPLE} />}
                  ></Select>
                </Form.Item>
                <Form.Item name="queryQcIsNull" label="QC为空" valuePropName="checked" style={{ flex: 1 }}>
                  <Checkbox></Checkbox>
                </Form.Item>
              </div>
            ),
          },
          {
            label: '面料是否集约',
            name: 'fabricIntensive',
            type: 'Select',
            option: [
              { label: '非集约', value: 0 },
              { label: '集约', value: 1 },
            ],
          },
          {
            label: '面料订单状态',
            name: 'fabricOrderStatus',
            type: 'Select',
            option: [
              { label: '待下发', value: 0 },
              { label: '已下发', value: 1 },
            ],
          },
          {
            label: 'SPU商品',
            name: 'spuCode',
            type: 'Select',
            placeholder: '款式编码/款式名称/助记码',
            option: SpuOptions,
            config: {
              suffixIcon: null,
              showSearch: true,
              filterOption: false,
              optionFilterProp: 'label',
              onSearch: handleSearchSpuOptions,
              notFoundContent: <Empty description="请输入内容搜索" image={Empty.PRESENTED_IMAGE_SIMPLE} />,
              popupMatchSelectWidth: true,
            },
          },
          {
            label: 'SKU商品',
            name: 'skuCodeList',
            placeholder: '商品条码',
            type: 'Select',
            option: SkuOptions,
            config: {
              mode: 'tags',
              maxTagCount: 'responsive',
              notFoundContent: null,
            },
          },
          {
            label: '推送状态',
            name: 'pushStatus',
            type: 'Select',
            option: [{ label: '推送失败', value: '0' }],
            hidden: !isRoot,
          },
          {
            label: '异常标签',
            name: 'tag',
            type: 'Select',
            option: [
              { label: '订单驳回', value: 1 },
              { label: 'OTB额度不足', value: 2 },
            ],
            config: {
              optionRender: (option: any) => {
                return <div style={{ color: 'var(--warning-color)' }}>{option?.data?.label}</div>
              },
            },
          },
        ]}
        onFinish={(vals: any) => {
          console.log(vals, 'vals')
          setselectKeys([])
          setselectInfos([])
          const paramsData = {
            ...vals,
            statuses: vals?.statuses?.length > 0 ? vals?.statuses : null,
            queryClassIdList: tinyClassIds.length > 0 ? tinyClassIds : null,
            createTimeStart: vals?.createTimeStart?.[0] && dayjs(vals.createTimeStart[0]).format('YYYY-MM-DD HH:mm:ss'),
            createTimeEnd: vals?.createTimeStart?.[1] && dayjs(vals.createTimeStart[1]).format('YYYY-MM-DD HH:mm:ss'),
            officialOrderTimeStart:
              vals?.officialOrderTimeStart?.[0] && dayjs(vals.officialOrderTimeStart[0]).format('YYYY-MM-DD HH:mm:ss'),
            officialOrderTimeEnd:
              vals?.officialOrderTimeStart?.[1] && dayjs(vals.officialOrderTimeStart[1]).format('YYYY-MM-DD HH:mm:ss'),
            requiredArrivalTimeStart: isRoot
              ? vals?.requiredArrivalTimeStart?.[0] && dayjs(vals.requiredArrivalTimeStart[0]).format('YYYY-MM-DD')
              : null,
            requiredArrivalTimeEnd: isRoot
              ? vals?.requiredArrivalTimeStart?.[1] && dayjs(vals.requiredArrivalTimeStart[1]).format('YYYY-MM-DD')
              : null,
            supplierIdList: vals?.supplierIdList?.length > 0 ? vals?.supplierIdList : null,
            firstClassConfigIdList: vals?.firstClassConfigIdList?.length > 0 ? vals?.firstClassConfigIdList : null,
            year: vals.year ? vals.year : null,
            seasonCode: vals.seasonCode ? vals.seasonCode : null,
            queryQcIsNull: vals.queryQcIsNull ? 1 : null,
          }
          search({
            ...paramsData,
          })
          setCachePage({
            ...paramsData,
            tinyClassId: vals.queryClassIdList,
            SpuOptions,
            SupplierOption,
            searchOptions,
            UserOptions,
            UserOptionsByQcDropDown,
            current: 1,
            size: params.size,
          })
        }}
        onReset={() => {
          setselectKeys([])
          setselectInfos([])
          settinyClassIds([])
          const paramsData = {
            current: 1,
            size: 10,
            officialOrderTimeStart: dayjs(defaultDateRange[0]).format('YYYY-MM-DD HH:mm:ss'),
            officialOrderTimeEnd: dayjs(defaultDateRange[1]).format('YYYY-MM-DD HH:mm:ss'),
            billStatus: isRoot ? null : 1,
            statuses: isRoot ? [0, 1, 2, 3, 5] : [2],
          }
          setCachePage({
            ...paramsData,
          })
          reset()
        }}
        extra={
          <div className="table_extra_flex_wrapbox">
            <div className="table_extra_flex">
              <PermissionButton
                permission="addPurchase"
                type="primary"
                onClick={() => {
                  navigate('/purchase/order/add')
                }}
                icon={<PlusOutlined />}
              >
                新建采购订单
              </PermissionButton>
              {isRoot ? (
                <PermissionButton
                  permission="batchAddPurchase"
                  onClick={() => {
                    setTempcode(IMPORT_FILE_ENUM.PURCHASEW_ORDER_IMPORT)
                    setisUploadFileShow(true)
                  }}
                  icon={<ImportOutlined />}
                >
                  按批次导入采购订单
                </PermissionButton>
              ) : null}
              <PermissionButton
                permission="editDeliveryDate"
                onClick={() => {
                  setTempcode(IMPORT_FILE_ENUM.PURCHASEW_DELIVERYTIME_IMPORT)
                  setisUploadFileShow(true)
                }}
                icon={<ImportOutlined />}
              >
                批量填写供应链交期
              </PermissionButton>
              <PermissionButton
                permission="batchEditProgress"
                onClick={() => {
                  setTempcode(IMPORT_FILE_ENUM.PURCHASEW_PROCESS_IMPORT)
                  setisUploadFileShow(true)
                }}
                icon={<ImportOutlined />}
              >
                批量更新生产进度
              </PermissionButton>
              <PermissionButton
                permission="addQc"
                onClick={() => {
                  if (selectKeys.length === 0) {
                    message.warning('请选勾选订单！')
                    return
                  }
                  setqcOrderShow(true)
                }}
              >
                预约QC
              </PermissionButton>
              <PermissionButton
                permission="BatchChangeQC"
                onClick={() => {
                  if (selectKeys.length === 0) {
                    message.warning('请选勾选订单！')
                    return
                  }
                  changeQCModal.openModal()
                }}
                icon={<UserOutlined />}
              >
                QC变更
              </PermissionButton>
              <PermissionButton
                permission="BatchChangeDocumentary"
                onClick={() => {
                  if (selectKeys.length === 0) {
                    message.warning('请选勾选订单！')
                    return
                  }
                  changeTrackPersonModal.openModal()
                }}
                icon={<UserOutlined />}
              >
                跟单变更
              </PermissionButton>
              <PermissionButton
                permission="IssueFabricOrders"
                onClick={async () => {
                  if (selectKeys.length === 0) {
                    message.warning('请选勾选订单！')
                    return
                  }
                  const res = await getPurchaseFabric<PurchaseFabricOrderVO>({
                    purchaseOrderCodeList: selectInfos.map((item) => item.purchaseOrderCode),
                  })
                  if (res.code == 200 && res.data && res.data.length > 0) {
                    const flattenedDataFirst = flattenData(res?.data || [])
                    const sortedData = flattenedDataFirst
                      .sort((a: any, b: any) => a?.purchaseOrderCode.localeCompare(b?.purchaseOrderCode))
                      ?.map((item) => {
                        if (item?.supplierInfoList && item?.supplierInfoList.length === 1) {
                          const items = item?.supplierInfoList[0]
                          return {
                            ...item,
                            supplierCode: items?.supplierCode || null,
                            supplierName: items?.supplierName || null,
                            fabricUnitPrice: items?.fabricUnitPrice || null,
                            fabricUnit: items?.fabricUnit || null,
                            remark: items?.remark || null,
                            totalPrice: mathjs.format(
                              mathjs.multiply(
                                mathjs.bignumber(item?.colorFabricOrderQty || 0),
                                mathjs.bignumber(item?.fabricUnitPrice || 0),
                              ),
                              {
                                notation: 'fixed',
                                precision: 2,
                              },
                            ),
                          }
                        } else {
                          return item
                        }
                      })
                    setFabricTableData(sortedData)
                    DistributeFabricModal.openModal()
                  } else {
                    message.warning('未查询到订单数据！')
                  }
                }}
              >
                下发面料订单
              </PermissionButton>
              <PermissionButton
                permission="editListTransferRules"
                onClick={() => {
                  if (selectKeys.length === 0) {
                    message.warning('请选勾选订单！')
                    return
                  }
                  TransferRulesModal.openModal()
                }}
              >
                修改调拨规则
              </PermissionButton>
              {isRoot ? (
                <PermissionButton
                  permission="editDeliverLimit"
                  onClick={() => {
                    setgoodsLimitModalShow(true)
                  }}
                >
                  发货数量浮动比例配置
                </PermissionButton>
              ) : null}
              {isRoot && menuItems.length > 0 ? (
                <Dropdown
                  placement="bottomLeft"
                  menu={{
                    items: menuItems,
                    onClick: handleClickMore,
                  }}
                >
                  <Button>
                    更多操作
                    <DownOutlined />
                  </Button>
                </Dropdown>
              ) : null}
            </div>
            <div className="table_extra_flex">
              {menuItemsExport.length > 0 ? (
                <Dropdown
                  placement="bottomLeft"
                  menu={{
                    items: menuItemsExport,
                    onClick: handleClickMoreExport,
                  }}
                >
                  <Button>
                    导出
                    <DownOutlined />
                  </Button>
                </Dropdown>
              ) : null}
            </div>
          </div>
        }
      ></SearchForm>
      <CustomTable
        bordered
        isSelection
        selectRows={selectRows}
        selectedRowKeys={selectKeys}
        columns={useIndexColumns({
          navigate,
          onBillClick,
          onEditDeliveryTime,
          isRoot,
          canEdit: buttonCodeList.includes('editDeliveryDate'),
          EditTrackOrderPerson: buttonCodeList.includes('EditTrackOrderPerson'),
          tableData,
          settableData,
          UserOptions: UserOptionsW,
          setUserOptions: setUserOptionsW,
          handleSearchUser: handleSearchUserW,
          onSaveUser,
        })}
        {...tableProps}
        tableRowGray={(record) => (record.status && record.status == 4 ? 'table-row-gray' : '')}
        isScrollY
        extraHeight={isRoot ? 64 : 0}
      />
      <Drawer
        title="审核订单"
        maskClosable
        open={auditDrawerShow}
        onClose={onCancel}
        footer={
          <div className="flex_end">
            <Space>
              <Button onClick={onCancel}>取消</Button>
              <Button type="primary" onClick={() => formAudit.validateFields().then((values) => onConfirmData(values))}>
                确定
              </Button>
            </Space>
          </div>
        }
      >
        <EditFormVertical
          editConfig={useFormAudit({ formAudit })}
          form={formAudit}
          initialValues={{ auditStatus: 1 }}
        />
      </Drawer>
      <Modal
        width={1000}
        title="账期明细数据"
        maskClosable
        open={billModalShow}
        onCancel={onCancel}
        footer={
          CurrentInfo.billStatus == 0 ? (
            <PermissionButton
              permission="confirmPurchaseFinance"
              type="primary"
              onClick={() => onConfirmBillSingle()}
              loading={billConfirmLoading}
            >
              确认账期
            </PermissionButton>
          ) : null
        }
      >
        <div className="header_table_style">
          {billTableInfo?.purchaseOrderFinance ? (
            <div style={{ marginBottom: 20 }}>付款条件：{billTableInfo?.purchaseOrderFinance}</div>
          ) : null}
          <Table
            loading={billTableLoading}
            bordered
            pagination={false}
            scroll={{
              x: 'max-content',
            }}
            columns={useBillDetailColumns()}
            rowHoverable={false}
            rowClassName={(_, index) => {
              return index % 2 === 0 ? '' : 'zebra-row-odd'
            }}
            dataSource={billTableInfo.billInfoList}
          ></Table>
        </div>
      </Modal>
      <Drawer
        title="预约QC"
        maskClosable
        open={qcOrderShow}
        onClose={onCancel}
        footer={
          <div className="flex_end">
            <Space>
              <Button onClick={onCancel}>取消</Button>
              <Button type="primary" onClick={() => formQc.validateFields().then((values) => onConfirmQC(values))}>
                确定
              </Button>
            </Space>
          </div>
        }
      >
        <EditFormVertical editConfig={useFormQc()} form={formQc} />
      </Drawer>
      <Modal
        title="发货数量浮动比例配置"
        maskClosable
        open={goodsLimitModalShow}
        onCancel={() => {
          onCancel()
          getProductClassConfig()
        }}
        footer={
          <Button type="primary" onClick={() => onConfirmGoodsLimit()}>
            确认
          </Button>
        }
      >
        <div className="header_table_style">
          <Table
            bordered
            pagination={false}
            columns={useLimitColumns({
              classIdOptionsTable,
              setclassIdOptionstable,
            })}
            dataSource={classIdOptionsTable}
            rowKey="value"
            childrenColumnName="aaaaaa"
            rowHoverable={false}
            rowClassName={(_, index) => {
              return index % 2 === 0 ? '' : 'zebra-row-odd'
            }}
          ></Table>
        </div>
      </Modal>
      <Modal title="供应链交期" open={isModalShow} onCancel={onModalCancel} onOk={onSendOk}>
        <Form form={FormDelivery} layout="vertical">
          <Form.Item
            label="供应链交期"
            name="deliveryTime"
            style={{ marginBottom: 0 }}
            rules={[
              {
                required: true,
                message: '请选择供应链交期',
              },
              {
                validator: (_: any, value: any) =>
                  TwoDateVerifyCanEqual(
                    _,
                    _,
                    value,
                    CurrentInfo?.requiredArrivalTime,
                    '供应链交期不能晚于要求到货日期',
                  ),
              },
            ]}
          >
            <DatePicker
              minDate={
                CurrentInfo?.requiredArrivalTime
                  ? dayjs(CurrentInfo?.requiredArrivalTime).subtract(10, 'day')
                  : undefined
              }
              maxDate={CurrentInfo?.requiredArrivalTime ? dayjs(CurrentInfo?.requiredArrivalTime) : undefined}
            ></DatePicker>
          </Form.Item>
        </Form>
      </Modal>
      <Modal
        title="驳回原因"
        open={isReturnModalShow}
        onCancel={onModalCancel}
        onOk={onReturnBack}
        confirmLoading={exportLoading}
      >
        <Form form={FormReturnBack} layout="vertical">
          <Form.Item
            label="驳回原因"
            name="rejectRemark"
            style={{ marginBottom: 0 }}
            rules={[
              {
                required: true,
                message: '请填写驳回原因',
              },
            ]}
          >
            <Input.TextArea placeholder="请输入驳回原因"></Input.TextArea>
          </Form.Item>
        </Form>
      </Modal>
      <ImportFileModal
        loading={exportLoading}
        open={isUploadFileShow}
        onCancel={onUploadFileCancel}
        onOk={onUploadFileOk}
        form={FormUpload}
        tempCode={tempCode}
      ></ImportFileModal>
      <Modal
        title="修改调拨规则"
        open={TransferRulesModal.open}
        maskClosable
        onCancel={TransferRulesModal.closeModal}
        footer={
          <div className="flex_end">
            <Space>
              <Button onClick={TransferRulesModal.closeModal}>取消</Button>
              <Button
                type="primary"
                loading={TransferRulesModal.confirmLoading}
                onClick={() => {
                  TransferRulesModal.handleSubmit((vals) =>
                    updateTransferRule({
                      ...vals,
                      purchaseOrderCodes: selectInfos.map((item) => item.purchaseOrderCode),
                    }),
                  )
                }}
              >
                确定
              </Button>
            </Space>
          </div>
        }
      >
        <EditFormVertical
          editConfig={[
            {
              name: 'transferType',
              label: '调拨规则',
              type: 'Radio',
              placeholder: '请选择调拨规则',
              option: TRANSFER_TYPE_OPTIONS,
              rules: [
                {
                  required: true,
                  message: '请选择调拨规则',
                },
              ],
            },
          ]}
          form={TransferRulesModal.form}
          initialValues={{ transferType: 3 }}
        />
      </Modal>
      <Modal
        width="100%"
        title="下发面料订单"
        open={DistributeFabricModal.open}
        maskClosable
        loading={DistributeFabricModal.confirmLoading}
        onCancel={DistributeFabricModal.closeModal}
        footer={
          <div className="flex_end">
            <Space>
              <Button onClick={DistributeFabricModal.closeModal}>取消</Button>
              <Button
                type="primary"
                loading={DistributeFabricModal.confirmLoading}
                onClick={() => {
                  const flattenedData = FabricTableData.map((item) => {
                    return {
                      ...item,
                      unitUsedNum: item.myunitUsedNum || 0,
                    }
                  })
                  console.log(flattenedData, 'flattenedData')
                  if (flattenedData?.some((item) => !item?.supplierCode)) {
                    message.warning('请填写完整面料供应商！')
                    return
                  }
                  if (flattenedData?.some((item) => !item?.unitUsedNum)) {
                    message.warning('请填写完整单件用量！')
                    return
                  }
                  if (flattenedData?.some((item) => !item?.colorFabricOrderQty)) {
                    message.warning('请填写完整色布实际下单量！')
                    return
                  }
                  if (flattenedData?.some((item) => !item?.intentDate)) {
                    message.warning('请填写完整面料意向交期！')
                    return
                  }
                  DistributeFabricModal.handleSubmit(() => savePurchaseFabric(flattenedData))
                }}
              >
                确定
              </Button>
            </Space>
          </div>
        }
      >
        <Table
          className="distribute_fabric_modal_wrap"
          size="small"
          loading={DistributeFabricModal.confirmLoading}
          bordered
          pagination={false}
          scroll={{
            x: 'max-content',
            y: 600,
          }}
          columns={useFabricTableDataColumns({
            isRoot,
            FabricTableData,
            setFabricTableData,
          })}
          rowHoverable={false}
          dataSource={FabricTableData}
          rowKey={(rows) =>
            (rows.purchaseOrderCode || '') +
            (rows.useSite || '') +
            (rows.colorCode || '') +
            (rows.colorFabricCode || '')
          }
        ></Table>
      </Modal>
      <Modal
        width={600}
        title="QC变更"
        open={changeQCModal.open}
        maskClosable
        onCancel={changeQCModal.closeModal}
        footer={
          <div className="flex_end">
            <Space>
              <Button onClick={changeQCModal.closeModal}>取消</Button>
              <Button
                type="primary"
                loading={changeQCModal.confirmLoading}
                onClick={() => {
                  changeQCModal.handleSubmit((vals) => {
                    return purchaseOrderUpdateQC({
                      ...vals,
                      ids: selectKeys,
                    })
                  })
                }}
              >
                确定
              </Button>
            </Space>
          </div>
        }
      >
        <div style={{ width: 300 }}>
          <EditFormVertical
            editConfig={useChangeQCConfig({
              UserOptions: UserOptionsByQc,
              handleSearchUser: handleSearchUserByQc,
            })}
            form={changeQCModal.form}
            initialValues={{ impactDeliveryTime: 0 }}
          />
        </div>
      </Modal>
      <Modal
        width={600}
        title="跟单变更"
        open={changeTrackPersonModal.open}
        maskClosable
        onCancel={changeTrackPersonModal.closeModal}
        footer={
          <div className="flex_end">
            <Space>
              <Button onClick={changeTrackPersonModal.closeModal}>取消</Button>
              <Button
                type="primary"
                loading={changeTrackPersonModal.confirmLoading}
                onClick={() => {
                  changeTrackPersonModal.handleSubmit((vals) => {
                    const trackOrderPerson = UserOptionsByTrackPerson?.find(
                      (item) => item?.value == vals?.trackOrderPersonWorkId,
                    )?.name
                    return purchaseOrderUpdateTrackPerson({
                      ...vals,
                      trackOrderPerson,
                      ids: selectKeys,
                    })
                  })
                }}
              >
                确定
              </Button>
            </Space>
          </div>
        }
      >
        <div style={{ width: 300 }}>
          <EditFormVertical
            editConfig={useChangeTrackPersonConfig({
              UserOptions: UserOptionsByTrackPerson,
              handleSearchUser: handleSearchUserByTrackPerson,
            })}
            form={changeTrackPersonModal.form}
            initialValues={{ impactDeliveryTime: 0 }}
          />
        </div>
      </Modal>
      <Spin spinning={spinning} fullscreen />
    </PageContainer>
  )
}

export default Index
